import Cocoa
import UniformTypeIdentifiers

@main
class AppDelegate: NSObject, NSApplicationDelegate {

    var statusItem: NSStatusItem?
    private let wallpaperManager = WallpaperManager.shared
    private var manageWindowController: ManageWallpapersWindowController?

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        NSApp.setActivationPolicy(.accessory)
        setupStatusItem()
        rebuildMenu()
        loadLastWallpaper()
        
        if wallpaperManager.getIsRandomSwitching() {
            wallpaperManager.startRandomSwitching()
        }
    }

    func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
        return true
    }

    // MARK: - Menu Management

    private func setupStatusItem() {
        statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
        if let button = statusItem?.button {
            button.image = NSImage(systemSymbolName: "display", accessibilityDescription: "Live Desktop")
        }
        // Listen for history changes to rebuild the menu
        NotificationCenter.default.addObserver(self, selector: #selector(rebuildMenu), name: .wallpaperHistoryChanged, object: nil)
        // Also rebuild the menu when the wallpaper is changed from anywhere
        NotificationCenter.default.addObserver(self, selector: #selector(rebuildMenu), name: .setWallpaper, object: nil)
    }

    @objc private func rebuildMenu() {
        let menu = NSMenu()

        menu.addItem(NSMenuItem(title: "添加壁纸...", action: #selector(addNewWallpaper), keyEquivalent: "n"))
        menu.addItem(NSMenuItem.separator())

        let currentWallpaperURL = wallpaperManager.getLastSelectedWallpaper()
        let history = wallpaperManager.getHistory()
        if history.isEmpty {
            let placeholderItem = NSMenuItem(title: "没有最近的壁纸", action: nil, keyEquivalent: "")
            placeholderItem.isEnabled = false
            menu.addItem(placeholderItem)
        } else {
            let recentHistory = history.prefix(10)
            for url in recentHistory {
                let menuItem = NSMenuItem(
                    title: url.lastPathComponent,
                    action: #selector(selectWallpaperFromHistory(_:)),
                    keyEquivalent: ""
                )
                menuItem.representedObject = url
                if url == currentWallpaperURL { menuItem.state = .on }
                menu.addItem(menuItem)
            }
        }
        
        menu.addItem(NSMenuItem.separator())
        menu.addItem(NSMenuItem(title: "壁纸管理...", action: #selector(openManageWindow), keyEquivalent: ","))
        menu.addItem(NSMenuItem(title: "清除壁纸", action: #selector(clearCurrentWallpaper), keyEquivalent: ""))
        menu.addItem(NSMenuItem.separator())
        
        let modeMenu = NSMenu()
        
        let currentMode = wallpaperManager.getLastDisplayMode() ?? "aspectFill"
        
        let aspectFillItem = NSMenuItem(title: "充满屏幕", action: #selector(changeDisplayMode(_:)), keyEquivalent: "")
        aspectFillItem.representedObject = "aspectFill"
        if currentMode == "aspectFill" { aspectFillItem.state = .on }
        modeMenu.addItem(aspectFillItem)

        let fillItem = NSMenuItem(title: "拉伸以充满屏幕", action: #selector(changeDisplayMode(_:)), keyEquivalent: "")
        fillItem.representedObject = "fill"
        if currentMode == "fill" { fillItem.state = .on }
        modeMenu.addItem(fillItem)

        let fitItem = NSMenuItem(title: "适合于屏幕", action: #selector(changeDisplayMode(_:)), keyEquivalent: "")
        fitItem.representedObject = "fit"
        if currentMode == "fit" { fitItem.state = .on }
        modeMenu.addItem(fitItem)

        let centerItem = NSMenuItem(title: "居中", action: #selector(changeDisplayMode(_:)), keyEquivalent: "")
        centerItem.representedObject = "center"
        if currentMode == "center" { centerItem.state = .on }
        modeMenu.addItem(centerItem)
        
        let modeItem = NSMenuItem(title: "图片缩放模式", action: nil, keyEquivalent: "")
        menu.setSubmenu(modeMenu, for: modeItem)
        menu.addItem(modeItem)
        
        // Random Switch Menu
        let randomSwitchItem = NSMenuItem(title: "随机切换壁纸", action: #selector(toggleRandomSwitching), keyEquivalent: "")
        randomSwitchItem.state = wallpaperManager.getIsRandomSwitching() ? .on : .off
        
        let switchIntervalMenu = NSMenu()
        let currentInterval = wallpaperManager.getWallpaperSwitchInterval()
        
        let intervals: [String: TimeInterval] = [
            "1 分钟": 60,
            "5 分钟": 300,
            "15 分钟": 900,
            "30 分钟": 1800,
            "1 小时": 3600
        ]
        
        for (title, interval) in intervals.sorted(by: { $0.value < $1.value }) {
            let item = NSMenuItem(title: title, action: #selector(changeSwitchInterval(_:)), keyEquivalent: "")
            item.representedObject = interval
            if currentInterval == interval {
                item.state = .on
            }
            switchIntervalMenu.addItem(item)
        }
        
        menu.setSubmenu(switchIntervalMenu, for: randomSwitchItem)
        menu.addItem(randomSwitchItem)
        
        menu.addItem(NSMenuItem.separator())
        
        let isPlaying = wallpaperManager.getIsPlaying()
        let playbackTitle = isPlaying ? "暂停" : "播放"
        let playbackItem = NSMenuItem(title: playbackTitle, action: #selector(togglePlayback), keyEquivalent: "p")
        menu.addItem(playbackItem)

        let isMuted = wallpaperManager.getIsMuted()
        let muteTitle = isMuted ? "取消静音" : "静音"
        let muteItem = NSMenuItem(title: muteTitle, action: #selector(toggleMute), keyEquivalent: "i")
        menu.addItem(muteItem)
        
        menu.addItem(NSMenuItem.separator())
        
        menu.addItem(NSMenuItem(title: "退出", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))

        statusItem?.menu = menu
    }

    // MARK: - Actions
    
    @objc private func toggleRandomSwitching() {
        let isEnabled = !wallpaperManager.getIsRandomSwitching()
        wallpaperManager.setIsRandomSwitching(isEnabled)
        rebuildMenu()
    }
    
    @objc private func changeSwitchInterval(_ sender: NSMenuItem) {
        guard let interval = sender.representedObject as? TimeInterval else { return }
        wallpaperManager.setWallpaperSwitchInterval(interval)
        
        // Ensure random switching is enabled when an interval is selected
        if !wallpaperManager.getIsRandomSwitching() {
            wallpaperManager.setIsRandomSwitching(true)
        }
        
        rebuildMenu()
    }
    
    @objc private func togglePlayback() {
        let newIsPlaying = !wallpaperManager.getIsPlaying()
        wallpaperManager.setIsPlaying(newIsPlaying)
        NotificationCenter.default.post(name: .togglePlayback, object: nil)
        rebuildMenu()
    }

    @objc private func toggleMute() {
        let newIsMuted = !wallpaperManager.getIsMuted()
        wallpaperManager.setIsMuted(newIsMuted)
        NotificationCenter.default.post(name: .toggleMute, object: nil)
        rebuildMenu()
    }

    @objc private func addNewWallpaper() {
        let openPanel = NSOpenPanel()
        let imageTypes: [UTType] = [.jpeg, .png, .heic]
        let videoTypes: [UTType] = [.quickTimeMovie, .mpeg4Movie]
        openPanel.allowedContentTypes = imageTypes + videoTypes
        
        openPanel.begin { [weak self] response in
            guard let self = self, response == .OK, let url = openPanel.url else { return }
            
            _ = url.startAccessingSecurityScopedResource()
            
            self.wallpaperManager.addWallpaper(url: url)
            self.postSetWallpaperNotification(for: url)
        }
        rebuildMenu() // 重新刷新菜单显示勾选
    }

    @objc private func selectWallpaperFromHistory(_ sender: NSMenuItem) {
        guard let url = sender.representedObject as? URL else { return }
        wallpaperManager.setLastSelectedWallpaper(url: url)
        postSetWallpaperNotification(for: url)
        rebuildMenu() // 重新刷新菜单显示勾选
    }
    
    @objc private func openManageWindow() {
        if manageWindowController == nil {
            manageWindowController = ManageWallpapersWindowController()
            // Nil out the controller when the window closes
            manageWindowController?.window?.delegate = self
        }
        manageWindowController?.showWindow(self)
    }
    
    @objc private func clearCurrentWallpaper() {
        wallpaperManager.clearLastSelectedWallpaper()
        postClearWallpaperNotification()
        rebuildMenu() // 重新刷新菜单显示勾选
    }
    
    @objc private func changeDisplayMode(_ sender: NSMenuItem) {
        guard let mode = sender.representedObject as? String else { return }
        wallpaperManager.setLastDisplayMode(mode) // 保存模式
        NotificationCenter.default.post(name: .init("changeImageDisplayMode"), object: nil, userInfo: ["mode": mode])
        rebuildMenu() // 重新刷新菜单显示勾选
    }

    private func loadLastWallpaper() {
        guard let url = wallpaperManager.getLastSelectedWallpaper() else { return }
        
        guard url.startAccessingSecurityScopedResource() else {
            return
        }
        postSetWallpaperNotification(for: url)
        url.stopAccessingSecurityScopedResource()
    }

    // MARK: - Notifications

    private func postSetWallpaperNotification(for url: URL) {
        NotificationCenter.default.post(name: .setWallpaper, object: nil, userInfo: ["url": url])
    }
    
    private func postClearWallpaperNotification() {
        NotificationCenter.default.post(name: .clearWallpaper, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension AppDelegate: NSWindowDelegate {
    func windowWillClose(_ notification: Notification) {
        // When the management window is closed, release its controller
        if (notification.object as? NSWindow) == manageWindowController?.window {
            manageWindowController = nil
        }
    }
}

